package com.jdk.learn.thread;

/**
 * 生产消费者问题
 */
public class ProductAndConsumer02 {
    public static void main(String[] args) {
        User user=new User();
        Product02 product=new Product02(user);
        Consumer02 consumer=new Consumer02(user);
        product.start();
        consumer.start();
    }
}

class Product02 extends Thread {
    private User user;
    public Product02(User user) {
        this.user=user;
    }

    @Override
    public void run() {
        int count=0;
        while (true) {
            //加锁 可保证数据的正确性  但是不一定是写线程先执行  可能user对象是null  而且不是交替执行 即生产一个消费一个
            synchronized (user) {
                if (count == 0) {
                    user.setUserName("老黄");
                    user.setAge(20);
                } else {
                    user.setUserName("老赵");
                    user.setAge(50);
                }
                count = (count + 1) % 2;
//            System.out.println("count:"+count);
            }
        }
    }
}

class Consumer02 extends Thread {
    private User user;
    public Consumer02(User user) {
        this.user=user;
    }

    @Override
    public void run() {
        synchronized (user) {
        while (true) {
            System.out.println(user);
        }
        }
    }
}
